package com.test.service.impl;

import com.test.entity.Book;
import com.test.entity.Borrow;
import com.test.entity.User;
import com.test.entity.UserBorrowView;
import com.test.feign.BookFeignClient;
import com.test.feign.UserFeignClient;
import com.test.mapper.BorrowMapper;
import com.test.service.BorrowService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Resource
    private BorrowMapper borrowMapper;
    @Resource
    private BookFeignClient bookFeignClient;
    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public UserBorrowView getBorrowViewByUid(int uid) {
        List<Borrow> borrowList = borrowMapper.getBorrowsByUid(uid);
        User user = userFeignClient.findUserById(uid);
        List<Book> bookList = new ArrayList<>();
        borrowList.forEach(o -> bookList.add(bookFeignClient.getBookById(o.getBid())));
        return new UserBorrowView(user, bookList);
    }

//    @Override
//    public UserBorrowView getBorrowViewByUid(int uid) {
//        // 现在拿到借阅关联信息了，怎么调用其他服务获取信息呢？
//        List<Borrow> borrowList = borrowMapper.getBorrowsByUid(uid);
//        // RestTemplate 支持多种方式的远程调用
//        RestTemplate template = new RestTemplate();
//        // 这里通过调用 getForObject 来请求其他服务，并将结果自动进行封装
//        // 获取 User 信息
//        User user = template.getForObject("http://127.0.0.1:8083/user/"+uid, User.class);
//        List<Book> bookList = new ArrayList<>();
//        for(Borrow borrow: borrowList) {
//            // 获取每一本 Book 信息
//            Book book = template.getForObject("http://127.0.0.1:8081/book/"+borrow.getBid(), Book.class);
//            bookList.add(book);
//        }
//        return new UserBorrowView(user, bookList);
//    }
}
